'''
s7 客户端
pip install python-snap7
pip install python-snap7[cli]
https://blog.csdn.net/pista/article/details/113405915
启动模拟服务端命令 snap7-server
'''

import snap7

# # 创建通讯客户端实例
# client = snap7.client.Client()
#
# # 连接至PLC
# client.connect('127.0.0.1', 0, 1, 1102) # 请求大小为480B的pdu
#
#
# print(f"连接状态：{client.get_connected()}")
#
#
# from snap7.types import Areas
#
# # 写
# data = bytearray([1,2,3,4])
# aaa = client.write_area(Areas.DB, 0, 0, data)
# # client.db_write(10,0,data)
#
#
# # 读
# buffer = client.read_area(Areas.DB, 0, 0, 111)
# print(buffer)
# print(len(buffer))
# print(buffer[0])
# print(buffer[1])
# print(buffer[2])
# print(buffer[3])
#
# value = snap7.util.get_real(buffer, 0)
#
# # 关闭连接
# # client.disconnect()
#
# # 打印连接状态
# print(f"连接状态：{client.get_connected()}")


class S7Client:

    def __init__(self, ip='127.0.0.1', port=1102):
        # 创建通讯客户端实例
        self.client = snap7.client.Client()
        self.ip = ip
        self.port = port

    def connect(self):
        # 连接至PLC
        try:
            self.client.connect(self.ip, 0, 0, self.port)  # 请求大小为480B的pdu
        except Exception as e:
            print(e)
        print(f"客户端 是否连接到 plc服务端：{self.client.get_connected()}")

    def get_connected(self):
        return self.client.get_connected()

    def read(self):
        '''
        读 （固定 Areas - index , 起始位， 长度 ）
        :return: buffer bytearray
        '''
        buffer = self.client.read_area(snap7.types.Areas.DB, 76, 0, 40) # server.register_area(srvAreaDB, 0, DBdata)
        # value = snap7.util.get_real(buffer, 0)
        return buffer

    def write(self, data):
        '''
        写 （固定 Areas - index， 起始位）
        :param data: bytearray or bytes
        :return:
        '''
        # data = bytes([1,2,3,4])
        self.client.write_area(snap7.types.Areas.DB, 76, 0, data)
        return None

    def close(self):
        self.client.disconnect()
        print(f"连接状态：{self.client.get_connected()}")

if __name__ == "__main__":
    # 建立模拟服务端
    # python D:\soft\Python38\Lib\site-packages\snap7\server\__main__.py
    from snap7 import util
    # 建立客户端
    cl = S7Client('192.168.0.1',  102)
    # cl = S7Client()
    cl.connect()

    # 写
    # data = bytes([1,2,3,4])
    data = bytearray(4)
    util.set_real(data,0, 12.345)
    cl.write(data)

    # 读
    out_data = cl.read()

    rea = util.get_real(out_data, 4)
    print(rea)
    # print
    print(out_data)
    # import struct
    # struct.u
    for i in range(0,len(out_data)):
        print(out_data[i])

    cl.close()